package com.king.framework.manager.factory;

import java.util.Date;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.king.common.constant.Constants;
import com.king.common.enums.SsEnum;
import com.king.common.utils.ServletUtils;
import com.king.common.utils.ip.AddressUtils;
import com.king.common.utils.ip.IpUtils;
import com.king.common.utils.spring.SpringUtils;
import com.king.common.utils.text.StringUtils;
import com.king.modules.monitor.domain.SysLoginLogEntity;
import com.king.modules.monitor.domain.SysOperLogEntity;
import com.king.modules.monitor.service.SysLoginLogService;
import com.king.modules.monitor.service.SysOperLogService;
import com.king.modules.system.domain.SysUserEntity;
import com.king.modules.system.service.SysUserService;

import eu.bitwalker.useragentutils.UserAgent;

/**
 * 异步工厂（产生任务用）
 * 
 * @author king
 */
public class AsyncFactory {
	
	private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

	/**
	 * 记录登录信息
	 * 
	 * @param username
	 *            用户名
	 * @param status
	 *            状态
	 * @param message
	 *            消息
	 * @param args
	 *            列表
	 * @return 任务task
	 */
	public static TimerTask recordLoginLog(final String username, final String status, final String message,
			final Object... args) {
		final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
		final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
		return new TimerTask() {
			@Override
			public void run() {
				String address = AddressUtils.getRealAddressByIP(ip);
				StringBuilder s = new StringBuilder();
				s.append(StringUtils.getBlock(ip));
				s.append(address);
				s.append(StringUtils.getBlock(username));
				s.append(StringUtils.getBlock(status));
				s.append(StringUtils.getBlock(message));
				// 打印信息到日志
				sys_user_logger.info(s.toString(), args);
				// 获取客户端操作系统
				String os = userAgent.getOperatingSystem().getName();
				// 获取客户端浏览器
				String browser = userAgent.getBrowser().getName();
				
				Date ts = new Date();
				// 封装对象
				SysLoginLogEntity loginlog = new SysLoginLogEntity();
				loginlog.setUserName(username);
				loginlog.setIpaddr(ip);
				loginlog.setLoginLocation(address);
				loginlog.setBrowser(browser);
				loginlog.setOs(os);
				loginlog.setMsg(message);
				// 日志状态
				if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
					loginlog.setStatus(Constants.SUCCESS);
				} else if (Constants.LOGIN_FAIL.equals(status)) {
					loginlog.setStatus(Constants.FAIL);
				}
				loginlog.setSs(SsEnum.NORMAL.getKey());
				try {
					SysUserEntity user = SpringUtils.getBean(SysUserService.class).selectUserByUserName(username);
					if(user != null){
						loginlog.setGroupid(user.getGroupid());
						loginlog.setCr(user.getId());
						loginlog.setMr(user.getId());
					}
				} catch (Exception e) {
					sys_user_logger.error(e.getLocalizedMessage());
				}
				loginlog.setCts(ts);
				loginlog.setMts(ts);
				// 插入数据
				SpringUtils.getBean(SysLoginLogService.class).insertLoginlog(loginlog);
			}
		};
	}

	/**
	 * 操作日志记录
	 * 
	 * @param operLog
	 *            操作日志信息
	 * @return 任务task
	 */
	public static TimerTask recordOperLog(final SysOperLogEntity operLog) {
		return new TimerTask() {
			@Override
			public void run() {
				// 远程查询操作地点
				operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
				SpringUtils.getBean(SysOperLogService.class).insertOperlog(operLog);
			}
		};
	}
}
